﻿using Microsoft.AspNetCore.Http;
using RxxAdmin.Common;
using RxxAdmin.Model;
using RxxAdmin.Model.Entity;
using SqlSugar;
using ICacheService = RxxAdmin.Common.ICacheService;

namespace RxxAdmin.Service
{
    public class SysUserService: ISysUserService
    {
        private readonly SqlSugarRepository<SysUser> _sysUserRep;
        private readonly ITokenService _tokenService;
        private readonly IHttpContextAccessor _httpContext;
        private readonly ICacheService _cacheService;

        public SysUserService(SqlSugarRepository<SysUser> sysUserRep, 
            ITokenService tokenService,
            IHttpContextAccessor httpContext,
            ICacheService cacheService)
        {
            _sysUserRep = sysUserRep;
            _tokenService = tokenService;
            _httpContext = httpContext;
            _cacheService = cacheService;
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<SysUserLoginOut> Login(SysUserLoginIn input)
        {

            var user = await _sysUserRep
                .Where(t => t.LoginName.ToLower() == input.Account.ToLower()).FirstAsync();

            if (user == null)
            {
                throw new Exception("该账户不存在");
            }
            if (user.LoginPWD != Md5Util.Encrypt(input.PassWord).ToUpper())
            {
                throw new Exception("密码输入错误");
            }
            if (user.Status != 1)
            {
                throw new Exception("该账户已被冻结");
            }


            TokenData tokenData = new TokenData
            {
                UserId = user.Id,
                UserAccount = user.LoginName,
                UserRolesId = user.RoleIds,
            };

            _tokenService.RemoveCheckToken(tokenData.UserId);
            string UserToken = _tokenService.GenerateToken(_httpContext.HttpContext, tokenData);


            return new SysUserLoginOut() { Id = user.Id, Name = user.LoginName, Token = UserToken };
        }

        /// <summary>
        /// 获取用户的信息
        /// </summary>
        /// <returns></returns>

        public async Task<GetUserInfoOut> GetUserInfo()
        {
            var user = await _sysUserRep.Where(t => t.Id == TokenInfo.User.UserId).FirstAsync();
            return new GetUserInfoOut()
            {
                userId = user.Id,
                userName = user.LoginName,
                roles = new List<string> { },
                buttons = new List<string> { }
            };
        }
    }
}
